package com.ptit.piclient;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Timer;
import java.util.TimerTask;

import com.ptit.piclient.model.Song;
//import com.ptit.piclient.tools.PiConnector;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

public class NowPlayingActivity extends Activity implements OnClickListener {
	//Textviews
	TextView tvSongname;
	TextView tvCurrentTime, tvDuration ;
	
	SeekBar progressbar;
	
	//Buttons
	Button btnPrev, btnNext, btnPlay, btnPause, btnStop, btnPlaylist, btnRepeat, btnShuffle;
	
	
	Song currentSong, tmpSong;
	int currentPosition = 0;
	Timer timer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_now_playing);
		tvSongname = (TextView) findViewById(R.id.songTitle);
		progressbar = (SeekBar) findViewById(R.id.songProgressBar);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		try {
			Intent i = getIntent();
			byte[] arr = i.getByteArrayExtra("currentsong");
			currentSong = NowPlayingActivity.deserialize(arr);
			tvSongname.setText(currentSong.getName() + " - " + currentSong.getFormatedArtist());
			progressbar.setMax(currentSong.getDuration());			
			currentPosition = 0;
			timer = new Timer();
			timer.schedule(new ProgressBarUpdater(), 0, 1000);
		} catch (Exception e) {
			Log.e("errornafy", e.getMessage());
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

	/**
	 * Retrieve song object from byte array
	 */
	public static Song deserialize(byte[] data) throws IOException,
			ClassNotFoundException {
		ByteArrayInputStream in = new ByteArrayInputStream(data);
		ObjectInputStream is = new ObjectInputStream(in);
		return (Song) is.readObject();
	}

	/**
	 * This class is a timetask that update progressbar while player is playing
	 * a song
	 */
	class ProgressBarUpdater extends TimerTask {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			currentPosition++;
			progressbar.setProgress(currentPosition);
		}

	}
}
